//
//  UserDetailViewController.m
//  小汽车
//
//  Created by mill on 15/1/10.
//  Copyright (c) 2015年 蓝欧科技. All rights reserved.
//

#import "UserDetailViewController.h"
#import "UserDetailTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "UserDetailModel.h"

@interface UserDetailViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>

@end

@implementation UserDetailViewController



- (void)dealloc
{

    [_tableView release];
    [_placeHodel release];
    [_imageName release];
    [_background release];
    [_uid release];
    [_level release];
    [_sex release];
    [_registTime release];
    [_image1 release];
    [super dealloc];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.cellArray = [NSMutableArray arrayWithObjects:@"用户名:",@"性别:",@"地区:",@"生日:",@"注册时间:",@"账号等级:", nil];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.title = @"个人资料";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(backAction:)];
    
    [self createView];
    [self createTableView];
}

-(void)backAction:(id)sender
{
    [self.delegate SendPictureImage:self.image1 changeSex:self.changeSex];
    [self.navigationController popToRootViewControllerAnimated:YES];
}
-(void)createView
{
    self.placeHodel = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height / 3 )];
    _placeHodel.backgroundColor = [UIColor colorWithWhite:0.8 alpha:0.6];
    [_tableView addSubview:_placeHodel];
    
    
    self.imageName = [[UIButton alloc] init];
    _imageName.backgroundColor = [UIColor cyanColor];
    _imageName.frame = CGRectMake(0, 0, self.placeHodel.frame.size.width / 5 *2, self.placeHodel.frame.size.height / 6 * 5);
    
    if (_image1) {
        [_imageName setBackgroundImage:_image1 forState:UIControlStateNormal];
    }else{
        NSURL *url = [NSURL URLWithString:_background];
        NSData *show = [NSData dataWithContentsOfURL:url];
        UIImage *image = [UIImage imageWithData:show];
        
        [_imageName setBackgroundImage:image forState:UIControlStateNormal];
    }
    
    
    _imageName.center = _placeHodel.center;
    [_imageName addTarget:self action:@selector(pictureAction:) forControlEvents:UIControlEventTouchUpInside];
    [_placeHodel addSubview:_imageName];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, _imageName.frame.size.height / 7 * 6, self.imageName.frame.size.width, self.imageName.frame.size.height / 7)];
    label.backgroundColor = [UIColor colorWithWhite:0.6 alpha:0.6];
    label.alpha = 0.3;
    label.text = @"编辑";
    label.font = [UIFont fontWithName:@"Helvetica-Bold" size:21];
    label.textColor = [UIColor colorWithRed:17.0/255.0 green:190.0/255.0 blue:227.0/255.0 alpha:1.0];
    label.textAlignment = NSTextAlignmentCenter;
    [_imageName addSubview:label];
    
    [_placeHodel release];
    [label release];
    [_imageName release];
}
#warning 访问相机,相册
-(void)pictureAction:(UIButton *)button
{
    //在这里呼出下方菜单按钮项
    myActionSheet = [[UIActionSheet alloc]
                     initWithTitle:nil
                     delegate:self
                     cancelButtonTitle:@"取消"
                     destructiveButtonTitle:nil
                     otherButtonTitles: @"打开照相机", @"从手机相册获取",nil];
    
    [myActionSheet showInView:self.view];
    [myActionSheet release];
    
}




- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    if (actionSheet == myActionSheet) {
        //呼出的菜单按钮点击后的响应
        if (buttonIndex == myActionSheet.cancelButtonIndex)
        {
            NSLog(@"取消");
        }
        
        switch (buttonIndex)
        {
            case 0:  //打开照相机拍照
                [self takePhoto];
                break;
                
            case 1:  //打开本地相册
                [self LocalPhoto];
                break;
        }
        
    }else if (actionSheet == sexActionSheet){
        switch (buttonIndex)
        {
            case 0:
            {
                _sex = @"男";
                self.changeSex = _sex;
                NSIndexSet * nd=[[NSIndexSet alloc]initWithIndex:1];//刷新第二个section
                [_tableView reloadSections:nd withRowAnimation:UITableViewRowAnimationMiddle];
                [self.delegate SendPictureImage:self.image1 changeSex:self.changeSex];
            }
                break;
                
            case 1:
            {
                _sex = @"女";
                self.changeSex = _sex;
                NSIndexSet * nd=[[NSIndexSet alloc]initWithIndex:1];//刷新第二个section
                [_tableView reloadSections:nd withRowAnimation:UITableViewRowAnimationMiddle];
                [self.delegate SendPictureImage:self.image1 changeSex:self.changeSex];
            }
                
                break;
        }
    }
    
    
}


//开始拍照
-(void)takePhoto
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        picker.allowsEditing = YES;
        picker.sourceType = sourceType;
        [self presentModalViewController:picker animated:YES];
        [picker release];
    }else
    {
        NSLog(@"模拟其中无法打开照相机,请在真机中使用");
    }
}

//打开本地相册
-(void)LocalPhoto
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    //设置选择后的图片可被编辑
    picker.allowsEditing = YES;
    [self presentModalViewController:picker animated:YES];
    
    [picker release];
}

//当选择一张图片后进入这里
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info

{
    
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"])
    {
        //先把图片转成NSData
        UIImage* image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        NSData *data;
        if (UIImagePNGRepresentation(image) == nil)
        {
            data = UIImageJPEGRepresentation(image, 1.0);
        }
        else
        {
            data = UIImagePNGRepresentation(image);
        }
        
        
        //图片保存的路径
        //这里将图片放在沙盒的documents文件夹中
        NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        
        
        //文件管理器
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        //把刚刚图片转换的data对象拷贝至沙盒中 并保存为image.png
        [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
        [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/image.png"] contents:data attributes:nil];
        
        //得到选择后沙盒中图片的完整路径
        filePath = [[NSString alloc]initWithFormat:@"%@%@",DocumentsPath,  @"/image.png"];
        
        //关闭相册界面
        [picker dismissModalViewControllerAnimated:YES];
        self.image1 = image;
        [_imageName setBackgroundImage:image forState:UIControlStateNormal];
    }
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    NSLog(@"您取消了选择图片");
    [picker dismissModalViewControllerAnimated:YES];
}



-(void)sendInfo
{
    NSLog(@"图片的路径是：%@", filePath);
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
/***************************************/
-(void)createTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    _tableView.tableHeaderView = _placeHodel;
    _tableView.backgroundColor = [UIColor colorWithWhite:0.9 alpha:0.6];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView registerClass:[UserDetailTableViewCell class] forCellReuseIdentifier:@"cell1"];
    self.tableView.tableFooterView = [[UIView alloc] init];
    [self.view addSubview:_tableView];
    
    [_tableView release];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 5;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 35;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [_cellArray count];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UserDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell1"];
    cell.leftLabel.text = [self.cellArray objectAtIndex:indexPath.section];
    cell.leftLabel.textColor = [UIColor colorWithWhite:0.8 alpha:0.9];
    if (indexPath.section == 0) {
        cell.attribute.text = [NSString stringWithFormat:@"xuser%@",self.uid];
        cell.rightImage = nil;
    }else if (indexPath.section == 1) {
        cell.attribute.text = _sex;
    }else if (indexPath.section == 2){
        cell.attribute.text = @"";
    }else if (indexPath.section == 3){
        cell.attribute.text = @"";
    }else if (indexPath.section == 4){
        cell.rightImage = nil;
        cell.attribute.text = _registTime;
    }else{
        cell.rightImage = nil;
        cell.attribute.text = _level;
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 1){
        sexActionSheet = [[UIActionSheet alloc]
                          initWithTitle:nil
                          delegate:self
                          cancelButtonTitle:@"取消"
                          destructiveButtonTitle:nil
                          otherButtonTitles: @"男", @"女",nil];
        
        [sexActionSheet showInView:self.view];
        [sexActionSheet release];
        
    }
    if (indexPath.section == 2) {
       
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
